package com.example.demo.controller;

import com.example.demo.entity.LoginParam;
import com.example.demo.entity.LoginUser;
import com.example.demo.entity.User;
import com.example.demo.service.DemoService;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2023/11/28
 */

@Slf4j
@Controller
@RequestMapping("/test")
public class DemoController {
    @Autowired
    private DemoService demoService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;


    @PostMapping("/login")
    @ResponseBody
    public String login(@RequestBody User loginParam) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginParam.getUserName(), loginParam.getPassWord());
        // 调用UserDetailsServiceImpl.loadUserByUsername
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)){
            return "用户名或密码错误，请重新登入";
        }
        // 获取登入用户的完整信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String jwt = jwtUtil.createJwt(loginUser.getUsername());
        // 将用户信息存入redis中

        redisUtil.setCacheObject(loginUser.getUsername(), loginUser, 10, TimeUnit.MINUTES);
        log.info("jwt: {}", jwt);
        return jwt;
    }

    @PostMapping("/register")
    @ResponseBody
    public String register(@RequestBody LoginParam loginParam) {
        if (StringUtils.hasText(loginParam.getUserName()) && StringUtils.hasText(loginParam.getPassWord())) {
            int count = demoService.register(loginParam);
            if (count > 0) {
                log.info("新用户注册成功");
                return "新用户注册成功";
            } else {
                log.info("用户创建失败！请重新创建");
                return "用户创建失败！请重新创建";
            }
        }
        return "请重新输入用户名和密码";
    }

    @GetMapping("/index")
    @ResponseBody
    @PreAuthorize("hasAuthority('select')")
    public String index() {
        return "success";
    }
}
